package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.HeapProblem;

import java.util.PriorityQueue;

/**
 * @author tzp
 * @since 2020/10/14
 */
public class LC215_1 implements HeapProblem {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
        for (int num : nums) {
            if (priorityQueue.size() < k) {
                priorityQueue.add(num);
            } else {
                if (num > priorityQueue.peek()) {
                    priorityQueue.remove();
                    priorityQueue.add(num);
                }
            }
        }
        return priorityQueue.remove();
    }
    //错误, 不用建这么大的堆
//    public int findKthLargest(int[] nums, int k) {
//        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Comparator.reverseOrder());
//        for (int num : nums) {
//            priorityQueue.add(num);
//        }
//        Integer result = null;
//        for (int i = 0; i < k; i++) {
//            result = priorityQueue.remove();
//        }
//        return result;
//    }


    public static void main(String[] args) {
        int[] a = {3, 2, 1, 5, 6, 4};
        System.out.println(new LC215_1().findKthLargest(a, 1));
        System.out.println(new LC215_1().findKthLargest(a, 2));
        System.out.println(new LC215_1().findKthLargest(a, 3));
        System.out.println(new LC215_1().findKthLargest(a, 4));
    }
}
